<?php

declare(strict_types=1);

namespace App\Repository\User;

use App\Model\User;
use App\Repository\Cache\UserCacheRepository;
use Hyperf\Di\Annotation\Inject;
use App\Model\UserProfiles;

class UserProfilesRepository
{
    #[Inject]
    private UserProfiles $userProfilesModel;

    #[Inject]
    private UserCacheRepository $userCacheRepository;

    #[Inject]
    private User $userModel;


    /**
     * 创建资料用户
     * @param array $data
     */
    public function create(array $data): void
    {
        $this->userProfilesModel->create($data);
    }

    /**
     * 根据用户id获取用户的详细信息
     * @param string|$id
     * @return array
     */
    public function getDataById(string $id): array
    {
        // 获取缓存数据
        $user = $this->userCacheRepository->getUserInfoById($id);
        if (empty($user['profile'])) {
            $profile = $this->userProfilesModel->where("user_id", $id)->select(["*"])->first();
            if ($profile) {
                $profile = $profile->toArray();

                // 存入用户详细信息
                $user['profile'] = $profile;

                // 设置缓存数据
                $this->userCacheRepository->setUserInfoByEmail($id, $user);
                return  $profile;
            } else {
                return [];
            }
        }else{
            return $user['profile'];
        }
    }

    /**
     * 跟新用户详细信息
     * @param array $data
     * @param string $id
     * @return void
     */
    public function updateData(array $data, string $id): void
    {
        // 跟新数据库
        $this->userProfilesModel->where("user_id", $id)->update($data);

        // 用户信息
        $userData = $this->userCacheRepository->getUserInfoById($id);

        // 跟新的数据
        $userData['profile'] = $data;

        // 跟新redis 数据
        $this->userCacheRepository->setUserInfoById($id, $userData);
    }

}